package com.sky.service.UserService.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.RedisConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.mapper.user.MerchantMapper;
import com.sky.mapper.user.UserMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.UserService.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.CategorySelectIdVO;
import com.sky.vo.UserLoginVO;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class UserServicelmpl implements UserService {
    private static final Logger log = LoggerFactory.getLogger(UserService.class);
    @Resource
    WeChatProperties weChatProperties;
    @Resource
    UserMapper userMapper;
    @Resource
    MerchantMapper merchantMapper;
    @Resource
    RedisTemplate redisTemplate;

    @Resource
    private JwtProperties jwtProperties;

    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<UserLoginVO> loginPrograms(UserLoginDTO userLoginDTO) {
        //HttpClient调用微信登录接口,获取到Openid
        String openId = getOpenId(userLoginDTO.getCode());
        //根据openId查询user用户表
        User user = userMapper.selectByOpenId(openId);
        // 没有新用户的话,就进行新用户注册
        if(Objects.isNull(user)){
            user = new User();
            user.setOpenid(openId);
            user.setCreateTime(LocalDateTime.now());
            int i = userMapper.insertUser(user);
            log.info("新增的数据{}",i);
        }
        // 如果查询到就生成toke
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        System.err.println  ("小程序获取到的token:"+token);
        //2.假设固定查询id=1的商家信息 根据电话来查
        Merchant merchant = merchantMapper.selectMerchant(1L);
        //3.需要计算商家和用户之间的配送费
        //商家的坐标
        String shopLocation = merchant.getLocation();
        // 用户坐标
        String userLonLat = userLoginDTO.getLocation();
        //计算配送费和计算距离
        BigDecimal delivoryCost = MapUtils.getDelivoryCost(shopLocation, userLonLat);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(openId)
                .token(token)
                .shopName(merchant.getShopName())
                .shopAddress(merchant.getShopAddress())
                .shopTelephone(merchant.getShopTelephone())
                .deliveryFee(delivoryCost)
                .shopId(merchant.getId()).build();
        return Result.success(userLoginVO);
    }

    @Override
    public List<CategorySelectIdVO> getByType() {
        List<CategorySelectIdVO> redisCategory = (List<CategorySelectIdVO>) redisTemplate.opsForValue().get(RedisConstant.USERCATEGORY_LIST);
        if(CollectionUtils.isNotEmpty(redisCategory)){
            System.err.println("小程序从缓存中查取数据");
            return redisCategory;
        }
        System.err.println("小程序从mysql中查取数据");
        redisCategory = userMapper.getByType();
        redisTemplate.opsForValue().set(RedisConstant.USERCATEGORY_LIST,redisCategory,60 * 60, TimeUnit.SECONDS);

        return redisCategory;
    }


    public String getOpenId(String code){
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        Map resMap = JSONObject.parseObject(json, Map.class);
        return resMap.get("openid").toString();
    }


}
